﻿/*盒子处理器*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Reflection;
using System.Web.Routing;

namespace Htss.Platform.Web
{
    public class InvokeBox
    {
        /// <summary>
        /// 存储指定的NameSpace,BoxName,ActionName
        /// </summary>
        public Dictionary<string, string> ActionBox
        {
            get;
            set;
        }
        public HttpContextBase HttpContext
        { get; set; }

        public RequestContext RequestContext
        {
            get;
            set;
        }
        /// <summary>
        /// 返回对象
        /// </summary>
        public Object ResultObject
        {
            get;
            set;
        }
        public InvokeBox(RequestContext RequestContext)
        {
            this.RequestContext = RequestContext;
            this.HttpContext = RequestContext.HttpContext;
        }
        /// <summary>
        /// 根据返回的TYPE 调用请求中的action
        /// </summary>
        public void Invoke()
        {
            Type resultType= FindBox();

            if (resultType != null)
            {
                Assembly assembly = Assembly.GetAssembly(resultType);

                var controllerInstance = assembly.CreateInstance(resultType.FullName);

                ((ControllerBox)controllerInstance).Init(RequestContext,ActionBox);
                //
                try
                {
                   //执行并接收返回信息
                    ResultObject = resultType.InvokeMember("Load", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, controllerInstance, null);
                }
                catch (HttpException e)
                {
                    HttpContext.Response.Write(e.Message+"<br/>"+e.Source);
                }
            }
            else
            {
                HttpContext.Response.Write("您找错地儿啦...");
            }
            
        }
        
        /// <summary>
        /// 查找当前请求所对应的盒子类
        /// </summary>
        /// <returns></returns>
        private Type FindBox()
        {
            //
            Type result = null;

            string boxNamespace = System.Web.Configuration.WebConfigurationManager.AppSettings["BoxNamespace"];
            //加载该类库下所有项目
            Assembly assembly = Assembly.Load(boxNamespace);

            //获取本次请求的盒子对象
            try
            {
                string box = boxNamespace + (ActionBox["NameSpace"] == "" ? "" : "." + ActionBox["NameSpace"]) + "." + ActionBox["BoxName"] + "Box";
                result = assembly.GetType(box);
            }
            catch { 
            }
            return result;
        }
    }
}
